<template>
  <div class="page-container">
    <el-container>
      <el-aside width="280px" class="page-aside" v-drag v-collapse>
        <div class="tree-box">
          <el-row>
            <el-input
              placeholder="搜索"
              v-model="filterText"
              style="margin-right: 10px"
              clearable
            />
          </el-row>
          <el-row class="page-aside-grow">
            <el-tree
              style="width: 100%"
              ref="tree"
              class="tree"
              node-key="id"
              v-loading="treeLoading"
              element-loading-text="数据加载中..."
              :data="treeData"
              :props="treeProps"
              :highlight-current="true"
              :default-expanded-keys="treeExpand"
              :expand-on-click-node="!treeCheck"
              :filter-node-method="filterNode"
              :show-checkbox="treeCheck"
              @node-click="nodeClick"
            >
              <template v-slot="{ data }">
                <div class="node-item">
                  <span class="node-label" :title="data.text"><span>{{data.text}}</span></span>
                </div>
              </template>
            </el-tree>
          </el-row>
        </div>
      </el-aside>
      <el-main class="page-main">
        <!--表格内容栏-->
        <ac-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          :checkRowOpShow="checkRowOpShow"
          @handleAjaxSuccess="handleAjaxSuccess"
          @handleTableOperator="handleTableOperator"
          @handleCellOperator="handleCellOperator"
        ></ac-table>
      </el-main>
    </el-container>

    <!--新增编辑界面-->
    <el-dialog
      :title="operator"
      width="800px"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-form
        :model="formData"
        label-width="120px"
        :disabled="!dialogEdit"
        :hide-required-asterisk="!dialogEdit"
        :rules="rules"
        ref="dataForm"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <ac-dict-select v-model="formData.type" dictCode="dictOrgType" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级部门" prop="parentId">
              <ac-organization v-model="formData.parentId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="ordinal">
              <el-input v-model.number="formData.ordinal" :min="1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有效" prop="valid">
              <ac-dict-radio v-model="formData.valid" dictCode="dictYesNo" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" :rows="5" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime">
              <ac-datetime v-model="formData.updateTime"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <ac-datetime v-model="formData.createTime"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { clearOrganization } from '@/utils/system';
import api from '@/http/api';

const tree = ref();
const filterText = ref('');
const treeLoading = ref(false);
const treeKey = ref('');
const treeData = ref([]);
const treeExpand = ref([]);
const treeProps = ref({
  children: 'children',
  label: 'text'
});
const treeCheck = ref(false);
const currNode = ref(null);

const filters = ref({
  name: '',
  type: '',
  parentId: ''
});
const filterFields = ref([
  {prop: "name", label: "名称"},
  {prop: "type", label: "类型", type: 'dict-select', dictCode: 'dictOrgType'},
]);
const columns = ref([
  {prop: "name", label: "名称", minWidth: 150, click: true},
  {prop: "type", label: "类型", width: 80, type: 'dict-select', dictCode: 'dictOrgType'},
  {prop: "unitName", label: "所属单位", minWidth: 150},
  {prop: "ordinal", label: "排序", width: 80, type: 'number'},
  {prop: "valid", label: "是否有效", width: 110, type: 'dict-select', dictCode: "dictYesNo"},
  {prop: "remark", label: "备注", minWidth: 100},
  {prop: "updateTime", label: "更新时间", width: 160, type: 'datetime'}
]);
const operator = ref('');
const dialogVisible = ref(false);
const dialogEdit = ref(true);
const editLoading = ref(false);
const formData = ref({parentId: '', button: null, valid: ''});
const rules = ref({
  name: [{required: true, message: '请输入名称', trigger: 'blur'}],
  type: [{required: true, message: '请选择类型', trigger: 'blur'}],
  valid: [{required: true, message: '请选择是否有效', trigger: 'change'}],
  ordinal: [
    {type: 'number', message: '排序必须为数字', trigger: 'blur'}
  ]
});
const dataTable = ref();
const dataForm = ref();

const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.indexOf(value) >= 0
    || (data.data.code != null && data.data.code.indexOf(value) >= 0);
};

const nodeClick = (data, treeNode) => {
  if (currNode.value && currNode.value.id === data.id) {
    treeNode.checked = !treeNode.checked;
  } else {
    treeNode.checked = true;
  }

  if (treeNode.checked) {
    currNode.value = data;
    filters.value.parentId = data.id || '';
    dataTable.value.refreshPage(1);
  } else {
    tree.value.setCurrentKey(null);
    currNode.value = null;
    filters.value.parentId = '';
    dataTable.value.refreshPage(1);
  }
};

const checkRowOpShow = (op, row) => {
  return !(op.name
    && ((op.name.indexOf('有效') >= 0 && row.valid === '1')
      || (op.name.indexOf('无效') >= 0 && row.valid === '0')));
};

const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogVisible.value = true;
  dialogEdit.value = false;
  operator.value = "查看";

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button})
  } else if(button.buttonType === 'add') {
    formData.value = {parentId: filters.value.parentId, button: button, valid: '1'};
  } else {
    formData.value = {parentId: filters.value.parentId, button: button, valid: '1'};
  }

  dialogVisible.value = true;
  dialogEdit.value = true;
  operator.value = button.name;
  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleAjaxSuccess = () => {
  loadTreeData();
};

const loadTreeData = () => {
  treeLoading.value = true;
  api.post('/system/organization/queryTree').then(res => {
    const node = tree.value.getCurrentNode();
    if (node !== undefined && node != null) {
      treeExpand.value = [node.id, node.data.parentId, '0'];
    } else {
      if (res.data.children.length > 0) {
        treeExpand.value = [res.data.children[0].id];
      } else {
        treeExpand.value = ['0'];
      }
    }
    treeData.value = res.data.children;
    treeLoading.value = false;
    if (treeKey.value) {
      nextTick(() => {
        tree.value.setCurrentKey(treeKey.value);
      });
    }
  }).catch(() => {
    treeLoading.value = false;
  });
};

const submitForm = () => {
  dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true
        api.post(formData.value.button.dataDestUrl, formData.value).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataForm.value && dataForm.value.clearValidate();
          dataTable.value.findPage();
          clearOrganization();
          loadTreeData();
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(()=>{});
    }
  });
};

watch(() => filterText.value, val => {
  tree.value.filter(val);
});

onMounted(() => {
  loadTreeData();
});
</script>

<style lang="scss" scoped>
.page-aside-grow {
  .node-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;

    .node-label {
      flex-grow: 1;
      width: 1px;
      text-overflow: ellipsis;
      overflow: hidden;
      display: flex;

      > span {
        width: 100%;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
}
:deep(.el-tree-node:not(.is-current):focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content:hover) {
  background-color: #f5f7fa!important;
}
:deep(.el-tree-node.is-current:focus>.el-tree-node__content) {
  background-color: #ecf5ff!important;
}
.node-item:hover {
  .node-button .node-button-item:hover {
    background: #eaeaea;
  }
}
.tree-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>